<?php

namespace app\company\service;

use app\company\model\CompanyDepartmentModel;
use app\company\model\CompanyEmployeeModel;
use app\company\model\CompanyPositionModel;
use app\exception\MsgException;
use app\model\UserModel;
use app\service\UserService;
use sword\service\FilterService;
use think\db\exception\DbException;
use think\facade\Db;
use think\Paginator;
use Throwable;

class EmployeeService extends Base
{

    /**
     * 获取表格数据
     * @param array $params
     * @return Paginator
     * @throws DbException
     */
    public function getList(array $params): Paginator
    {
        $pageSize = $params['pageSize']?? 10;
        $model = new CompanyEmployeeModel();

        $where = [];
        if(!empty($params['cid'])){
            $where[] = ['cid', '=', $params['cid']];
        }
        if(!empty($params['realname'])){
            $where[] = ['realname', 'like', "%{$params['realname']}%"];
        }
        if(!empty($params['dept_id'])){
            if(($params['dept_children'] ?? 'true') == 'true'){
                //包含子部门员工
                $ids = DepartmentService::getDeptIds($params['dept_id']);
                $where[] = ['dept_id', 'in', $ids];
            }else{
                //不包含
                $where[] = ['dept_id', '=', $params['dept_id']];
            }
        }

        //过滤器
        $filter = FilterService::format($params['_filter']??'', [
            'status' => 'company_employee.status', //员工状态
        ]);
        $where = array_merge($where, $filter);

        return $model->order('id', 'desc')
            ->where($where)
            ->withJoin([
                'user' => function($query) {
                    $query->withField('realname,mobile,sex');
                }
            ])
            ->paginate($pageSize)
            ->each(function($item){
                $item['position_name'] = CompanyPositionModel::where('id', $item['position_id'])->value('name');
                $item['dept_name'] = CompanyDepartmentModel::where('id', $item['dept_id'])->value('name');
                return $item;
            });
    }

    /**
     * 新增员工
     * @param array $data
     * @return CompanyEmployeeModel
     * @throws DbException|MsgException|Throwable
     */
    public function add(array $data): CompanyEmployeeModel
    {
        $model = new CompanyEmployeeModel();

        try{
            Db::startTrans();

            //查询用户是否已存在
            $user = UserModel::where('mobile', $data['mobile'])
                ->find();
            if(!$user){
                //注册新用户
                $user = (new UserService())->add([
                    'realname' => substr($data['mobile'], -4),
                    'mobile' => $data['mobile'],
                ]);
            }
            $data['uid'] = $user->id;

            if($this->checkExist($data)){
                throw new MsgException("该员工已存在", 501);
            }

            $model->save([
                'cid' => $data['cid'],
                'uid' => $data['uid'],
                'dept_id' => $data['dept_id'],
                'position_id' => $data['position_id'],
                'in_time' => strtotime($data['in_time'])
            ]);
            Db::commit();
        }catch (Throwable $e){
            Db::rollback();
            throw $e;
        }

        //新增员工
        return $model;
    }

    /**
     * 编辑
     * @param array $data
     * @return CompanyEmployeeModel
     * @throws Throwable
     */
    public function edit(array $data): CompanyEmployeeModel
    {
        $model = CompanyEmployeeModel::find($data['id']);
        $model->save($data);

        return $model;
    }

    /**
     * 批量删除
     * @param $ids
     * @return bool
     */
    public function delete($ids): bool
    {
        if(!is_array($ids)){
            $ids = [$ids];
        }

        foreach ($ids as $id){
            CompanyEmployeeModel::destroy($id);
        }
        return true;
    }

    /**
     * 检查员工是否已存在
     * @param array $data
     * @return ?int
     */
    public function checkExist(array $data) :?int
    {
        //判断员工是否已经添加
        return CompanyEmployeeModel::where([
            'cid' => $data['cid'],
            'uid' => $data['uid'],
            'out_time' => 0
        ])->value('id');
    }

}